package com.jackstraw.create.utils;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

/**
 * 版权所有： 稻草人
 * 所在包：com.jackstraw.create.utils
 * 文件名：
 * 项目：create
 * 功能描述：
 * 修改时间：2021-04-17 0:08
 *
 * @author jackstraw
 */
public class VelocityUtil {

    /**
     * 模板位置
     */
    private static String tptPath;

    /**
     * 模板引擎
     */
    private static VelocityEngine ve;

    /**
     * 构建模板引擎
     * @return
     */
    public static void initVelocityEngine(String templatePath) {
        if (ve == null) {
            ve = new VelocityEngine();
        }
        if (!templatePath.equals(tptPath)) {
            Properties properties = new Properties();
            properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
            ve.init(properties);
        }
    }

    /**
     * 根据模板生成文件
     * @param folderPath
     * @param fileName
     * @param templateName
     * @param context
     * @throws FileNotFoundException
     */
    public static void createFile(String folderPath, String fileName, String templateName, VelocityContext context) throws FileNotFoundException {
        createFolder(folderPath);
        Template template = ve.getTemplate(templateName, "utf-8");
        PrintWriter printWriter = new PrintWriter(folderPath + "/" + fileName);
        template.merge(context, printWriter);
        printWriter.close();
    }

    /**
     * 创建文件夹
     * @param folderPath
     */
    public static void createFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    /**
     * 构造上下文对象
     * @param map
     * @return
     */
    public static VelocityContext buildVelocityContextByMap(Map<String, Object> map) {
        VelocityContext context = new VelocityContext();
        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            String key = next.getKey();
            Object value = next.getValue();
            context.put(key, value);
        }
        return context;
    }
}
